/**************************************************************
 *@ProjectName: blweibo
 *@FileName: AccountManager.java
 *@Date: 2011-5-31
 *@Copyright: 2011 www.hrbanlv.com Inc. All rights reserved.
 **************************************************************/
package com.zhiweibo;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhiweibo.models.Account;
import com.zhiweibo.models.StaticInfo;
import com.zhiweibo.util.Helper;
import com.zhiweibo.util.HttpUtil;

/**
 * The Class AccountManager.
 * 
 * @author SunHaibin
 * @since Android 1.6
 * @history 2011-5-31
 */
public class AccountManager extends BaseActivity implements ListItemEventHandler {

    /** The Constant DELETE_ITEM. */
    public static final int DELETE_ITEM = 0;

    /** The Constant KEY_ITEM_POSITION. */
    public static final String KEY_ITEM_POSITION = "position";

    /** The Constant PRE_DELETE_ITEM. */
    public static final int PRE_DELETE_ITEM = 1;

    /** The wd. */
    private WeiboDB wd;

    /** The m accounts. */
    private static List mAccounts;

    /** The is edit state. */
    private boolean isEditState;

    /** The m state list. */
    private static List mStateList;

    /** The handler. */
    Handler handler;

    /** The lv account. */
    private ListView lvAccount;

    /** The m adapter. */
    private AccountAdapter mAdapter;

    /** The m task. */
    private LoginTask mTask;

    /** The m task free. */
    private boolean mTaskFree = true;

    /**
     * Instantiates a new account manager.
     */
    public AccountManager() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message paramMessage) {

                if (paramMessage.what == 0) {
                    removeItem(paramMessage.getData().getInt("position"));
                    mAdapter.notifyDataSetChanged();
                    if (AccountManager.mAccounts == null || AccountManager.mAccounts.size() == 0) {
                        StaticInfo.mPassword = "";
                        StaticInfo.mUsername = "";
                        StaticInfo.mUid = "";
                        StaticInfo.mNickName = "";
                        Helper.delString(AccountManager.this, "username");
                        Helper.delString(AccountManager.this, "password");
                        Helper.delString(AccountManager.this, "nickname");
                        Helper.delString(AccountManager.this, "uid");
                        startActivity(new Intent(AccountManager.this, SwitchUser.class));
                        finish();
                        Message m = new Message();
                        m.what = 2;
                        MainTabActivity.handle.sendMessage(m);
                    }
                }

            }
        };
    }

    /**
     * Removes the item.
     * 
     * @param paramInt
     *            the param int
     */
    private void removeItem(int paramInt) {
        mAccounts.remove(paramInt);
        mStateList.remove(paramInt);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.yingnet.zhiweibo.BaseActivity#handleTitleBarEvent(int)
     */
    @Override
    protected void handleTitleBarEvent(int paramInt) {
        if (paramInt == 0) {
            isEditState = !isEditState;
            if (isEditState) {
                setTitleBar(1, getString(R.string.imageviewer_back), getString(R.string.account_management),
                        getString(R.string.account_add_done));
            } else {
                setTitleBar(1, getString(R.string.imageviewer_back), getString(R.string.account_management),
                        getString(R.string.btn_accountmanager_edit));
            }
            if (mStateList == null) {
                mAdapter.notifyDataSetChanged();
            } else if (mStateList.size() == 0) {
                mAdapter.notifyDataSetChanged();
            } else {
                for (int i = 0; i < mStateList.size(); i++) {
                    String s5 = ((Account) mAccounts.get(i)).mUsername;
                    if (s5 != null) {
                        if (s5.equalsIgnoreCase(StaticInfo.mUsername)) {
                            mStateList.set(i, isEditState ? 4 : 0);
                        } else {
                            mStateList.set(i, isEditState ? 5 : 1);
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
        } else if (paramInt == 1) {
            AccountHelper.saveAccounts(this, mAccounts);
            if (AccountHelper.findAccount(mAccounts, StaticInfo.mUsername) != null || mAccounts == null
                    || mAccounts.size() == 0) {
                AccountHelper.saveAccounts(this, mAccounts);
                finish();
            } else {
                Account localAccount2 = (Account) mAccounts.get(0);
                mTask = new LoginTask();
                mTask.execute(localAccount2.mUsername, localAccount2.mPassword, localAccount2.mUid,
                        localAccount2.mNickName);
            }
        }

    }

    /*
     * (non-Javadoc)
     * 
     * @see com.yingnet.zhiweibo.BaseActivity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setView(R.layout.accountmanager);
        setTitleBar(1, getString(R.string.imageviewer_back), getString(R.string.account_management),
                getString(R.string.btn_accountmanager_edit));
        lvAccount = (ListView) findViewById(R.id.lvAccountManager);
        mAdapter = new AccountAdapter();
        isEditState = false;
        mAccounts = AccountHelper.loadAccounts(this);
        lvAccount.setAdapter(mAdapter);
        wd = WeiboDB.getInstance(AccountManager.this);
        lvAccount.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView paramAdapterView, View paramView, int paramInt, long paramLong) {
                if ((AccountManager.mAccounts != null) && (AccountManager.mAccounts.size() == paramInt)) {
                    startActivity(new Intent(AccountManager.this, SwitchUser.class));
                } else {
                    if (mTaskFree) {
                        Account localAccount = (Account) AccountManager.mAccounts.get(paramInt);
                        mTask = new LoginTask();
                        mTask.execute(new String[] { localAccount.mUsername, localAccount.mPassword, localAccount.mUid,
                                localAccount.mNickName });
                    }
                }
            }
        });
        if ((mAccounts != null) && (mAccounts.size() != 0)) {
            int k = mAccounts.size();
            mStateList = new ArrayList(k);
            for (int i = 0; i < k; i++) {
                if (((Account) mAccounts.get(i)).mUsername.equals(StaticInfo.mUsername)) {
                    mStateList.add(i, 0);
                } else {
                    mStateList.add(i, 1);
                }
            }
        } else {
            startActivity(new Intent(AccountManager.this, SwitchUser.class));
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        super.onResume();
        mAccounts = AccountHelper.loadAccounts(this);
        mAdapter.notifyDataSetChanged();
        if ((mAccounts != null) && (mAccounts.size() != 0)) {
            int k = mAccounts.size();
            mStateList = new ArrayList(k);
            for (int i = 0; i < k; i++) {
                if (((Account) mAccounts.get(i)).mUsername.equals(StaticInfo.mUsername)) {
                    mStateList.add(i, 0);
                } else {
                    mStateList.add(i, 1);
                }
            }
        } else {
            startActivity(new Intent(AccountManager.this, SwitchUser.class));
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
     */
    @Override
    public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {

        if (paramInt == 4) {
            if (!mTaskFree) {
                mTask.cancel(true);
            } else {
                if (isEditState) {
                    ly.rightButton.performClick();
                } else {
                    ly.leftButton.performClick();
                }
            }
            return true;
        } else {
            return super.onKeyDown(paramInt, paramKeyEvent);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onPause()
     */
    @Override
    protected void onPause() {
        super.onPause();
        List localList = mAccounts;
        AccountHelper.saveAccounts(this, localList);
    }

    /**
     * The Class AccountAdapter.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    class AccountAdapter extends BaseAdapter {

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getCount()
         */
        @Override
        public int getCount() {
            if (mAccounts == null) {
                return 1;
            } else {
                return mAccounts.size() + 1;
            }

        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getItem(int)
         */
        @Override
        public Object getItem(int paramInt) {
            return paramInt;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getItemId(int)
         */
        @Override
        public long getItemId(int paramInt) {
            return paramInt;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getView(int, android.view.View,
         * android.view.ViewGroup)
         */
        @Override
        public View getView(int i, View view, ViewGroup viewgroup) {
            int k = AccountManager.mAccounts.size();
            View obj = null;
            if (i == k) {
                View view1 = ((LayoutInflater) getSystemService("layout_inflater")).inflate(
                        R.layout.accountlistitemview, null);
                ImageView imageview = (ImageView) view1.findViewById(R.id.ivPoint);
                TextView textview = (TextView) view1.findViewById(R.id.tvAccountName);
                ImageView imageview1 = (ImageView) view1.findViewById(R.id.ivTrianle);
                android.graphics.drawable.Drawable drawable = getResources().getDrawable(R.drawable.account_item_add);
                imageview.setImageDrawable(drawable);
                textview.setText(R.string.add_new_account);
                textview.setPadding(0, 18, 0, 18);
                imageview1.setVisibility(View.INVISIBLE);
                view1.setBackgroundResource(R.drawable.list_bottom_line);
                obj = view1;
            } else {
                Account account = (Account) AccountManager.mAccounts.get(i);
                int l = ((Integer) AccountManager.mStateList.get(i)).intValue();
                obj = new AccountListItemView(AccountManager.this, account, i, l, AccountManager.this);
            }
            return obj;
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.yingnet.zhiweibo.ListItemEventHandler#dismissProgressBar()
     */
    @Override
    public void dismissProgressBar() {
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.yingnet.zhiweibo.ListItemEventHandler#handleListItemEvent(int,
     * int)
     */
    @Override
    public void handleListItemEvent(int paramInt1, int paramInt2) {
        String str = "position";
        switch (paramInt1) {
        case 0:
            Message localMessage1 = new Message();
            localMessage1.what = 0;
            Bundle localBundle1 = new Bundle();
            localBundle1.putInt(str, paramInt2);
            localMessage1.setData(localBundle1);
            handler.sendMessage(localMessage1);
            break;
        case 1:
            Message localMessage2 = new Message();
            localMessage2.what = 1;
            Bundle localBundle2 = new Bundle();
            localBundle2.putInt(str, paramInt2);
            localMessage2.setData(localBundle2);
            handler.sendMessage(localMessage2);
            break;
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.yingnet.zhiweibo.ListItemEventHandler#showProgressBar()
     */
    @Override
    public void showProgressBar() {
    }

    /**
     * The Class LoginTask.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    public class LoginTask extends AsyncTask<String, Integer, Boolean> {

        /** The pd. */
        private ProgressDialog pd;

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected Boolean doInBackground(String... as) {
            boolean b = HttpUtil.login(as[0], as[1]);
            if (b) {
                StaticInfo.mUsername = as[0];
                StaticInfo.mPassword = as[1];
                StaticInfo.mNickName = as[3];
                StaticInfo.mUid = as[2];
                Helper.saveString(AccountManager.this, "username", StaticInfo.mUsername);
                Helper.saveString(AccountManager.this, "password", StaticInfo.mPassword);
                Helper.saveString(AccountManager.this, "nickname", StaticInfo.mNickName);
                Helper.saveString(AccountManager.this, "uid", StaticInfo.mUid);
                for (int i = 10001; i < 10005; i++) {
                    WeiboEventService.delNo(i);
                }
            }
            return b;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onCancelled()
         */
        @Override
        protected void onCancelled() {
            mTaskFree = true;
            if (pd != null) {
                pd.dismiss();
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Boolean boolean1) {
            if (boolean1) {
                wd.deleteAllTopic();
                wd.deleteAllAt();
                wd.deleteAllComment();
                wd.deleteAllMessage();
                wd.deleteUser();
                StaticInfo.cleanDate();
                Helper.delString(AccountManager.this, "newId");
                Intent intent2 = new Intent(AccountManager.this, MainTabActivity.class);
                startActivity(intent2);
            } else {
                Toast.makeText(AccountManager.this, getString(R.string.login_failed), Toast.LENGTH_LONG).show();
            }
            if (pd != null) {
                pd.dismiss();
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            mTaskFree = false;
            pd = new ProgressDialog(AccountManager.this);
            pd.setMessage("登陆中……");
            pd.show();
        }
    }
}